package com.google.code.irouter.plugin.detector;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import org.apache.commons.lang.Validate;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.google.appengine.api.datastore.Link;
import com.google.code.irouter.batch.api.Detector;
import com.google.code.irouter.batch.api.DetectorResult;
import com.google.code.irouter.model.Guide;

public final class OpenApiDetector extends Detector {

	@SuppressWarnings("unchecked")
	@Override
	protected List<DetectorResult> resolve(Guide guide,
			InputStream inputStream, List<DetectorResult> result)
			throws Exception {
		SAXReader saxReader = new SAXReader();
		Document doc = saxReader.read(new InputStreamReader(inputStream,
				getDefaultCharset()));
		List<Element> nodes = doc.selectNodes("/urlset/url/data/display");
		for (Element node : nodes) {
			String resource = node.getParent().getParent().elementText("loc");
			String description = node.elementText("title");
			String imgSrc = node.elementText("image");
			DetectorResult detectorResult = new DetectorResult();
			detectorResult.setMessage(description);
			if(imgSrc != null) 
				detectorResult.setFile(new Link(imgSrc));
			try {
				Validate.notEmpty(resource);
				detectorResult.setLink(new Link(resource));
			} catch (IllegalArgumentException e) {
				detectorResult.setLink(null);
			}
			detectorResult.setFixedLink(guide.getFixedLink());		
			result.add(detectorResult);
		}
		return result;
	}

	@Override
	protected List<DetectorResult> resolve(Guide guide, String text,
			List<DetectorResult> result) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected boolean isReconnect(Exception exception, boolean result) {
		if(DocumentException.class.isInstance(exception))
			result = true;
		return result;
	}

	@Override
	protected LOAD_TYPE getLoadType() {
		return Detector.LOAD_TYPE.STREAM;
	}

}
